package cn.monkey.transport.netty.server.codec.protocol.tcp.mqtt;

import cn.monkey.transport.netty.utils.ChannelHandlerUtils;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLEngine;
import java.util.function.Consumer;

public interface MqttServerProtocolConsumer extends Consumer<Channel> {

    MqttServerProtocolConsumer INSTANCE = MqttServerProtocolConfig::defaultConfig;

    MqttServerProtocolConfig mqttServerConfig();

    @Override
    default void accept(Channel channel) {
        ChannelPipeline pipeline = channel.pipeline();
        MqttServerProtocolConfig mqttServerConfig = this.mqttServerConfig();
        SslContext sslContext = mqttServerConfig.getSslContext();
        if (sslContext != null) {
            SSLEngine sslEngine = sslContext.newEngine(ByteBufAllocator.DEFAULT);
            pipeline.addLast(new SslHandler(sslEngine));
        }
        pipeline.addLast(ChannelHandlerUtils.normalizeName(MqttDecoder.class), new MqttDecoder(mqttServerConfig.getMaxBytesInMessage(), mqttServerConfig.getMaxClientIdLength()))
                .addLast(ChannelHandlerUtils.normalizeName(MqttEncoder.class), MqttEncoder.INSTANCE);
    }
}
